<template>
  <div style="position: relative;">
      <div id="container" style="width: 100%; height: 800px;"></div>
      <div class="tools">
          <a-card class="box-card">
            <div slot="header" class="clearfix">
                <span>风机:{{info.modelId}}</span>
            </div>
            <a-button @click="starts(0)">001-开关</a-button>
            <a-button @click="status(0)">001-故障恢复</a-button>
            <a-button @click="gotolink('Wind')">路由跳转</a-button>
          </a-card>
      </div>
  </div>
</template>
<script>
import * as Three from 'three'
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

let mouse, raycaster

export default {
  data () {
    return {
      height: null,
      camera: null,
      scene: null,
      renderer: null,
      controls: null,
      windmill: [{
          lat:0,
          log:0,
          start: true,
          obj:null,
          info:{
              modelId:'001',
              status: 0
          }
      }],
      info:{
          modelId:''
      },
      timeIndex: null
    }
  },
  beforeDestroy(){
    cancelAnimationFrame(this.timeIndex);
  },
  methods: {
    getHeight() {
      this.height = window.innerHeight + "px";
    },
    init() {
      let container = document.getElementById('container')

      this.scene = new Three.Scene()

      this.camera = new Three.PerspectiveCamera(30, container.clientWidth / container.clientHeight, 0.01, 100000)
      this.camera.position.set(90, 0, 100)

      const gltfLoader = new GLTFLoader();

      let logoTexture = new Three.Texture();
      const imgLoader = new Three.ImageLoader();
      imgLoader.load(this.baseUrl + "/static/models/logo_m.png",function(img)
      {
          logoTexture.image = img;
          logoTexture.needsUpdate = true;
      });

      gltfLoader.load(this.baseUrl + "/static/models/windmill.gltf", (obj) => {
        obj.scene.children[0].children[2].material = new Three.MeshLambertMaterial({
            side: Three.DoubleSide,
            transparent: true,
            opacity: 1,
            map: logoTexture,
            alphaTest:0.1,
            shininess:10,
        })

        obj.scene.children[0].children[3].material = new Three.MeshLambertMaterial({
            side: Three.DoubleSide,
            transparent: true,
            opacity: 1,
            map: logoTexture,
            alphaTest:0.1,
            shininess:10,
        })

        for(let i = 0; i<this.windmill.length; i++){
            this.windmill[i].obj = obj.scene.clone()
            this.windmill[i].obj.children[0].children[0].children[0].material = obj.scene.children[0].children[0].children[0].material.clone()
            this.windmill[i].obj.position.set(this.windmill[i].lat, 0, this.windmill[i].log)
            this.scene.add(this.windmill[i].obj)
        }

      });

      let geometry = new Three.BoxGeometry( 60, 100, 20 );
      let material = new Three.MeshBasicMaterial( {opacity: 0, transparent: true, wireframe:true} );
        
        for(let i = 0; i<this.windmill.length; i++){
            let cube = new Three.Mesh( geometry, material );
            cube.position.set(this.windmill[i].lat, 50, this.windmill[i].log)
            cube.name = this.windmill[i].info.modelId
            this.scene.add( cube );
        }

      this.renderer = new Three.WebGLRenderer({ antialias: true, alpha: true, logarithmicDepthBuffer: true})
      this.renderer.setPixelRatio( window.devicePixelRatio );
      this.renderer.setSize(container.clientWidth, container.clientHeight)
      this.renderer.domElement.style.outline = "none"
      container.appendChild(this.renderer.domElement)

      this.controls = new OrbitControls(this.camera, this.renderer.domElement);
      this.controls.maxPolarAngle = Math.PI * 0.495;
	  this.controls.target.set( 0, 55, 0 );
      this.controls.minDistance = 40.0;
      this.controls.maxDistance = 700.0;
      this.controls.enablePan = false;
      this.controls.enableRotate = false;
      this.controls.enableZoom = false;
      this.controls.update();

      const ambient = new Three.AmbientLight(0x444444, 2.5);
      this.scene.add(ambient);

      const pointLight = new Three.PointLight(0xffffff, 0.5);
      pointLight.position.set(0, 400, 800);
      this.scene.add(pointLight);
      var pointLightHelper = new Three.PointLightHelper( pointLight, 10 );
    //   this.scene.add( pointLightHelper );

      window.addEventListener(
        "resize",
        () => {
            this.renderer.setSize(container.clientWidth, container.clientHeight);
            this.camera.aspect = container.clientWidth/container.clientHeight;
            this.camera.updateProjectionMatrix ();
        },
        false
      );

      raycaster = new Three.Raycaster();
      mouse = new Three.Vector2();

      window.addEventListener("click", this.onMouseClick, false);
    },
    onMouseClick(event) {
        mouse.x = (event.offsetX / window.innerWidth) * 2 - 1;
        mouse.y = -(event.offsetY / window.innerHeight) * 2 + 1;
        raycaster.setFromCamera(mouse, this.camera);
        let intersects = raycaster.intersectObjects(this.scene.children, true);
        
        intersects = intersects.filter((intersect) => {
            return !(intersects.object instanceof Three.GridHelper) &&
            intersect.object.name !== 'water' &&
            intersect.object.name !== 'sky'
        });

        this.info.modelId = intersects[0].object.name
    },
    animate() {
      this.timeIndex = requestAnimationFrame(this.animate)
      for(var i = 0; i<this.windmill.length; i++){
            if(this.windmill[i].start == true && this.windmill[i].obj !== null){
                this.windmill[i].obj.children[0].children[0].rotation.z += 0.005
            }
            if(this.windmill[i].info.status == 0 && this.windmill[i].obj !== null){
                this.windmill[i].obj.children[0].children[0].children[0].material.color.set("#ffffff")
            }else if(this.windmill[i].info.status == 1 && this.windmill[i].obj !== null){
                this.windmill[i].obj.children[0].children[0].children[0].material.color.set("#efdf6d")
            }else if(this.windmill[i].info.status == 2 && this.windmill[i].obj !== null){
                this.windmill[i].start = false
                this.windmill[i].obj.children[0].children[0].children[0].material.color.set("#e7425d")
            }
        }
        this.render()
    },
    render() {
        this.renderer.render(this.scene, this.camera)
    },
    starts(index) {
        this.windmill[index].start = !this.windmill[index].start
    },
    status(index) {
        this.windmill[index].info.status = 0
        this.windmill[index].start = true
    },
    gotolink(path){
        this.$router.replace(path)
    }
  },
  created() {
    window.addEventListener("resize", this.getHeight);
    this.getHeight();
  },
  mounted () {
    this.init()
    this.animate()
  }
}

</script>
<style lang="less" scoped>
#container {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background: url('~@/assets/images/wind_bg.jpg') no-repeat center;
  background-size: cover;
}

.tools{
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 3;
}

.box-card{
  .ant-btn + .ant-btn {
    margin-left: 10px;
  }
}
</style>